<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部个人信息区域 -->
    <view class="profile-header">
      <view class="header-background"></view>
      <view class="header-content">
        <view class="flex items-center justify-between mb-4">
          <text class="text-xl font-bold text-white">个人中心</text>
        </view>
        
        <view class="flex items-center space-x-4">
          <view class="profile-avatar-container" @click="uploadAvatar">
            <image :src="userInfo.avatar || userInfo.avatar_url || '/static/avatars/default-avatar.png'" 
                   alt="用户头像" 
                   class="profile-avatar" 
                   v-if="userInfo.avatar || userInfo.avatar_url"
                   mode="aspectFill">
            </image>
            <view class="avatar-placeholder" v-else>
              <text class="fas fa-user text-white"></text>
            </view>
            <view class="avatar-edit-overlay">
              <text class="fas fa-camera text-white text-sm"></text>
            </view>
          </view>
          <view class="flex-1">
            <text class="text-lg font-semibold mb-1 block text-white">{{ userInfo.nickname || userInfo.username || '未设置昵称' }}</text>
            <!-- <text class="text-blue-100 text-sm">ID: {{ userInfo._id || userInfo.id || '未知' }}</text> -->
            <text class="text-blue-100 text-xs mt-1 block" v-if="userInfo.create_time || userInfo.createdAt">注册于 {{ formatDate(userInfo.create_time || userInfo.createdAt) }}</text>
          </view>
          <button class="edit-profile-btn" @click="editProfile">
            <text class="fas fa-edit mr-1"></text>
            <text>编辑</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 收藏集管理入口 -->
    <view class="px-6 py-4 border-b border-gray-200">
      <view class="flex items-center justify-between mb-3">
        <text class="text-lg font-semibold">我的收藏集</text>
        <view class="text-blue-500 hover:text-blue-600 transition-colors" @click="goToCollectionManagement">
          <text class="fas fa-cog mr-1"></text>
          <text>管理</text>
        </view>
      </view>
      <!-- 收藏集横向滚动列表 -->
      <scroll-view class="collection-scroll-container" scroll-x="true" show-scrollbar="false">
        <view class="collection-scroll-wrapper">
          <!-- 动态收藏集列表 -->
          <view class="collection-item" 
                v-for="collection in collections" 
                :key="collection._id"
                @click="goToCollectionDetail(collection._id)">
            <view class="collection-card">
              <text class="collection-title">{{ collection.name }}</text>
              <text class="collection-count">{{ collection.pattern_count || 0 }}个图案</text>
            </view>
          </view>
          
          <!-- 默认收藏集（如果没有自定义收藏集） -->
          <view class="collection-item" v-if="collections.length === 0" @click="goToFavorites">
            <view class="collection-card">
              <text class="collection-title">我的收藏</text>
              <text class="collection-count">0个图案</text>
            </view>
          </view>
          
          <!-- 添加新收藏集按钮 -->
          <view class="collection-item" @click="createNewCollection">
            <view class="collection-card add-card">
              <text class="fas fa-plus collection-add-icon"></text>
              <text class="collection-add-text">添加收藏集</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 设置选项 -->
    <view class="px-6 py-4 border-b border-gray-200">
      <text class="text-lg font-semibold mb-4 block">设置</text>
      <view class="space-y-3">
        <!-- 账户安全 -->
        <view class="flex items-center justify-between p-3 bg-gray-50 rounded-xl" @click="goToAccountSecurity">
          <view class="flex items-center space-x-3">
            <view class="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center text-red-500">
              <text class="fas fa-shield-alt"></text>
            </view>
            <text class="font-medium">账户安全</text>
          </view>
          <view class="flex items-center space-x-2 text-gray-600">
            <text class="fas fa-chevron-right"></text>
          </view>
        </view>
        
        <!-- 语言设置 -->
        <view class="flex items-center justify-between p-3 bg-gray-50 rounded-xl" @click="changeLanguage">
          <view class="flex items-center space-x-3">
            <view class="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500">
              <text class="fas fa-globe"></text>
            </view>
            <text class="font-medium">语言设置</text>
          </view>
          <view class="flex items-center space-x-2 text-gray-600">
            <text>{{ currentLanguage }}</text>
            <text class="fas fa-chevron-right"></text>
          </view>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="px-6 py-4">
      <button class="logout-btn" @click="logout">
        <text class="fas fa-sign-out-alt mr-2"></text>
        <text>退出登录</text>
      </button>
    </view>

    <!-- 底部弹窗遮罩层 -->
    <view 
      class="fixed inset-0 bg-black bg-opacity-50 z-40 overlay"
      :class="{ 'active': showOverlay, 'hidden': !showOverlay }"
      @click="closeAllSheets"
    ></view>

    <!-- 底部弹窗 - 编辑个人资料 -->
    <view 
      class="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50 bottom-sheet"
      :class="{ 'active': showEditProfile, 'hidden': !showEditProfile }"
      style="max-height: 80vh; overflow-y: auto; -webkit-overflow-scrolling: touch;"
    >
      <view class="px-6 pt-6 pb-8 safe-area-bottom">
        <view class="flex items-center justify-between mb-6">
          <text class="text-lg font-bold">编辑个人资料</text>
          <view class="text-gray-400" @click="closeEditProfile">
            <text class="fas fa-times text-xl"></text>
          </view>
        </view>
        
        <!-- 头像选择 - 改进版 -->
        <view class="flex flex-col items-center mb-6">
          <view class="avatar-upload-container">
            <view class="avatar-preview">
              <image :src="previewAvatar || userInfo.avatar || userInfo.avatar_url || '/static/avatars/default-avatar.png'" 
                     alt="用户头像" 
                     class="w-full h-full object-cover"
                     mode="aspectFill"
                     v-if="previewAvatar || userInfo.avatar || userInfo.avatar_url">
              </image>
              <view class="avatar-placeholder" v-else>
                <text class="fas fa-user"></text>
              </view>
            </view>
            <view class="avatar-upload-overlay" @click="uploadAvatar">
              <text class="fas fa-camera"></text>
            </view>
          </view>
          <text class="text-blue-500 text-sm mt-2" @click="uploadAvatar">更换头像</text>
        </view>

        <!-- 用户名 -->
        <view class="mb-4">
          <text class="block text-sm font-medium text-gray-700 mb-1">用户名</text>
          <input type="text" v-model="editForm.username" class="w-full h-full px-4 py-3 h-12 rounded-xl border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 outline-none transition-all text-base" style="z-index: 60; position: relative; background-color: #fff;">
        </view>

        <view class="mb-4">
          <text class="block text-sm font-medium text-gray-700 mb-1">昵称</text>
          <input type="text" v-model="editForm.nickname" class="w-full h-full px-4 py-3 h-12 rounded-xl border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 outline-none transition-all text-base" style="z-index: 60; position: relative; background-color: #fff;">
        </view>

        <button class="w-full py-4 bg-blue-500 text-white rounded-xl font-medium text-lg mb-4" @click="saveProfile">
          保存
        </button>
      </view>
    </view>

    <!-- 底部弹窗 - 语言设置 -->
    <view 
      class="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50 bottom-sheet"
      :class="{ 'active': showLanguageSheet, 'hidden': !showLanguageSheet }"
      style="max-height: 80vh; overflow-y: auto; -webkit-overflow-scrolling: touch;"
    >
      <view class="px-6 pt-6 pb-8 safe-area-bottom">
        <view class="flex items-center justify-between mb-6">
          <text class="text-lg font-bold">选择语言</text>
          <view class="text-gray-400" @click="closeLanguageSheet">
            <text class="fas fa-times text-xl"></text>
          </view>
        </view>
        
        <view class="space-y-3">
          <view 
            v-for="lang in languages" 
            :key="lang.code"
            class="w-full flex items-center justify-between p-4 rounded-xl border border-gray-200 hover:border-blue-500 transition-colors"
            @click="selectLanguage(lang)"
          >
            <view class="flex items-center space-x-3">
              <text class="text-2xl">{{ lang.flag }}</text>
              <text class="font-medium">{{ lang.name }}</text>
            </view>
            <text v-if="currentLanguage === lang.name" class="fas fa-check text-blue-500"></text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { collectionApi } from '@/api/index.js'
  import { store, mutations } from '@/uni_modules/uni-id-pages/common/store.js'
  // 导入uni-id-co云对象类型，用于提示
  
  export default {
  name: 'Profile',
  data() {
    return {
      activeTab: 'myPatterns',
      showOverlay: false,
      showEditProfile: false,
      showLanguageSheet: false,
      currentLanguage: '简体中文',
      previewAvatar: '',
      
      userInfo: {},
      
      collections: [],
      
      safeAreaBottomHeight: 0, // 用于存储底部安全区域高度
      
      editForm: {
        username: '',
        nickname: '',
        bio: ''
      },
      
      languages: [
        { code: 'zh-CN', name: '简体中文', flag: '🇨🇳' },
        { code: 'zh-TW', name: '繁體中文', flag: '🇹🇼' },
        { code: 'en', name: 'English', flag: '🇺🇸' },
        { code: 'ja', name: '日本語', flag: '🇯🇵' },
        { code: 'ko', name: '한국어', flag: '🇰🇷' }
      ]
    }
  },
  
  onLoad() {
    this.loadUserInfo()
    this.loadUserCollections()
    this.getSystemInfo()
    
    // 恢复保存的语言设置
    const savedLanguage = uni.getStorageSync('selectedLanguage')
    if (savedLanguage) {
      const lang = this.languages.find(l => l.code === savedLanguage)
      if (lang) {
        this.currentLanguage = lang.name
      }
    }
    
    // 监听登录状态变化
    uni.$on('uni-id-pages-login', () => {
      this.loadUserInfo()
      this.loadUserCollections()
    })
    
    uni.$on('uni-id-pages-logout', () => {
      this.userInfo = {}
      this.collections = []
    })
  },
  
  // 每次页面显示时刷新用户信息
  onShow() {
    this.loadUserInfo()
  },
  
  // 支持下拉刷新
  onPullDownRefresh() {
    Promise.all([
      this.loadUserInfo(),
      this.loadUserCollections()
    ]).then(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  onUnload() {
    // 移除事件监听
    uni.$off('uni-id-pages-login')
    uni.$off('uni-id-pages-logout')
  },
  
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.getFullYear() + '年' + (date.getMonth() + 1) + '月'
    },
    
    // 加载用户收藏集
    async loadUserCollections() {
      try {

        const result = await collectionApi.getUserCollections();
        
        if (result.errCode === 0 && result.data) {
          this.collections = result.data.list || [];
          console.log('收藏集加载成功:', this.collections);
        } else {
          console.warn('获取收藏集失败:', result.errMsg || '未知错误');
          this.collections = [];
        }
      } catch (error) {
        console.error('加载收藏集失败:', error);
        this.collections = [];
        
        // 显示错误信息给用户
        uni.showToast({
          title: '加载收藏集失败: ' + (error.message || '网络错误'),
          icon: 'none'
        });
      }
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        // 从uni-id-pages store获取用户信息
        if (store.hasLogin) {
          // 使用云对象获取最新的用户信息
            
          try {
            // 回退到本地存储的用户信息
            let userInfo = uni.getStorageSync('uni-id-pages-userInfo')||{};
            this.userInfo = {
              ...userInfo,
              id: userInfo._id,
              name: userInfo.nickname || userInfo.username || '未设置昵称'
            };
            
          } catch (e) {
            console.error('获取最新用户信息失败，使用本地存储:', e);
            // 回退到本地存储的用户信息
            let userInfo = uni.getStorageSync('uni-id-pages-userInfo')||{};
            this.userInfo = {
              ...userInfo,
              id: userInfo._id,
              name: userInfo.nickname || userInfo.username || '未设置昵称'
            };
          }
          
          // 更新编辑表单
          this.editForm = {
            username: this.userInfo.username || '',
            nickname: this.userInfo.nickname || '',
            bio: this.userInfo.bio || ''
          };
        } else {
          // 如果未登录，跳转到登录页
          uni.reLaunch({
            url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
          });
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        });
      }
    },
    switchTab(tab) {
      this.activeTab = tab
    },
    
    editProfile() {
      // 确保编辑表单使用最新的用户信息
      this.editForm = {
        username: this.userInfo.username || this.userInfo.name || '',
        nickname: this.userInfo.nickname || this.userInfo.username || '',
        bio: this.userInfo.bio || ''
      }
      this.showEditProfile = true
      this.showOverlay = true
    },
    
    closeEditProfile() {
      this.showEditProfile = false
      this.showOverlay = false
      this.previewAvatar = ''
    },
    
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        // 直接选择压缩图片，无需额外压缩
        sizeType: ['compressed'], 
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 记录选择的图片路径格式，便于调试
          console.log('选择的图片路径:', tempFilePath);
          
          // 直接使用选择的图片路径作为预览
          this.previewAvatar = tempFilePath;
          
          // 如果在编辑模式下上传头像，只预览不立即上传
          if (this.showEditProfile) {
            return;
          }
          
          // 直接上传头像
          this.uploadAvatarToServer(tempFilePath);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    async uploadAvatarToServer(filePath) {
      uni.showLoading({
        title: '上传中...',
        mask: true
      });
      
      try {
        const uniIdCo = uniCloud.importObject("uni-id-co");
        
        // 获取当前用户信息，确保有用户ID
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
        if (!userInfo._id) {
          throw new Error('未找到有效的用户信息，请重新登录');
        }
        
        // 上传文件到云存储
        const uploadRes = await uniCloud.uploadFile({
          filePath: filePath,
          cloudPath: `avatar/${Date.now()}-${Math.random().toString(36).slice(-8)}.jpg`
        });
        
        if (!uploadRes.fileID) {
          throw new Error('上传失败');
        }
        
        // 使用updateUser方法更新头像，需要提供uid和头像fileID
        const updateRes = await uniIdCo.updateUser({
          uid: userInfo._id,
          username: userInfo.username || '', // 确保提供username参数
          avatar: uploadRes.fileID
        });
        
        if (updateRes.code === 0 || updateRes.errCode === 0) {
          // 更新本地用户信息
          this.userInfo.avatar = uploadRes.fileID;
          
          // 更新uni-id-pages中的用户信息
          const userInfoToUpdate = {
            ...uni.getStorageSync('uni-id-pages-userInfo'),
            avatar: uploadRes.fileID
          };
          uni.setStorageSync('uni-id-pages-userInfo', userInfoToUpdate);
          mutations.updateUserInfo({
            avatar: uploadRes.fileID
          });
          
          uni.hideLoading();
          uni.showToast({
            title: '头像更新成功',
            icon: 'success'
          });
        } else {
          throw new Error(updateRes.message || '更新头像失败');
        }
      } catch (error) {
        console.error('上传头像失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '上传失败: ' + (error.message || '网络错误'),
          icon: 'none'
        });
      }
    },
    
    changeLanguage() {
      this.showLanguageSheet = true
      this.showOverlay = true
    },
    
    closeLanguageSheet() {
      this.showLanguageSheet = false
      this.showOverlay = false
    },
    
    selectLanguage(lang) {
      this.currentLanguage = lang.name
      uni.setStorageSync('selectedLanguage', lang.code)
      
      uni.showToast({
        title: `已切换到${lang.name}`,
        icon: 'success'
      })
      
      this.closeLanguageSheet()
    },
    
    closeAllSheets() {
      this.showEditProfile = false
      this.showLanguageSheet = false
      this.showOverlay = false
      this.previewAvatar = ''
    },
    
    // 获取系统信息
    getSystemInfo() {
      try {
        const systemInfo = uni.getSystemInfoSync()
        // 判断是否是iPhone X以上的机型，需要考虑底部安全区域
        if (systemInfo.safeAreaInsets) {
          this.safeAreaBottomHeight = systemInfo.safeAreaInsets.bottom
        }
        console.log('系统信息:', systemInfo)
        console.log('安全区域底部高度:', this.safeAreaBottomHeight)
      } catch (e) {
        console.error('获取系统信息失败:', e)
      }
    },
    
    goToCollectionManagement() {
      uni.navigateTo({
        url: '/pages/collection/management'
      })
    },
    
    goToCollectionDetail(collectionId) {
      uni.navigateTo({
        url: `/pages/collection/detail?id=${collectionId}`
      })
    },
    
    createNewCollection() {
      uni.showModal({
        title: '新建收藏集',
        content: '请输入收藏集名称',
        editable: true,
        success: async (res) => {
          if (res.confirm && res.content) {
            try {
              const result = await collectionApi.createCollection({
                name: res.content.trim()
              })
              
              if (result.errCode === 0) {
                uni.showToast({
                  title: '创建成功',
                  icon: 'success'
                })
                // 重新加载收藏集列表
                this.loadUserCollections()
              } else {
                uni.showToast({
                  title: result.errMsg || '创建失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('创建收藏集失败:', error)
              uni.showToast({
                title: '创建失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 保存个人资料
    async saveProfile() {
      try {
        uni.showLoading({
          title: '保存中...',
          mask: true
        });
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
        
        // 确保有用户ID
        if (!userInfo._id) {
          throw new Error('未找到有效的用户信息，请重新登录');
        }

        // 简化更新数据，必须包含用户名(username)，uid是必须的
        const updateData = {
          uid: userInfo._id,  // uid 参数必须保留
          username: this.editForm.username || userInfo.username || ''  // 始终包含username字段
        };
        
        // 只包含实际修改的字段 - 昵称是可选的
        if (this.editForm.nickname && this.editForm.nickname !== userInfo.nickname) {
          updateData.nickname = this.editForm.nickname;
        }
        
        // 使用uni-id-co云对象更新用户资料
        const uniIdCo = uniCloud.importObject("uni-id-co");
        
        // 如果有新头像，先上传头像
        let avatarFileID = null;
        // 检查是否有本地图片文件（排除http/https开头的远程URL）
        if (this.previewAvatar && !this.previewAvatar.startsWith('http://') && !this.previewAvatar.startsWith('https://')) {
          try {
            console.log('准备上传本地头像文件:', this.previewAvatar);
            // 上传文件到云存储
            const uploadRes = await uniCloud.uploadFile({
              filePath: this.previewAvatar,
              cloudPath: `avatar/${Date.now()}-${Math.random().toString(36).slice(-8)}.jpg`
            });
            
            if (uploadRes.fileID) {
              avatarFileID = uploadRes.fileID;
              // 将头像文件ID添加到updateData对象中
              updateData.avatar = avatarFileID;
            }
          } catch (uploadError) {
            console.error('头像上传失败:', uploadError);
            // 头像上传失败不阻止其他信息的更新
            uni.showToast({
              title: '头像上传失败，但其他信息将继续更新',
              icon: 'none',
              duration: 2000
            });
          }
        }
        
        // 扩展字段放入userInfo中
        // const userInfoFields = {
        //   bio: this.editForm.bio
        // };
        
        // // 处理额外的用户信息字段
        // if (Object.keys(userInfoFields).length > 0) {
        //   updateData['user_info'] = userInfoFields;
        // }
        
        // 调用云对象更新用户信息
        const result = await uniIdCo.updateUser(updateData);
        
        uni.hideLoading();
        
        // 输出完整结果，便于调试
        console.log('更新用户信息结果:', JSON.stringify(result));
        
        if (result.code === 0 || result.errCode === 0) {
          // 合并userInfo中的字段到用户主信息中
          const updatedUserInfo = {
            ...this.userInfo,
            ...updateData
          };
          
          // if (userInfoFields.bio) {
          //   updatedUserInfo.bio = userInfoFields.bio;
          // }
          
          if (avatarFileID) {
            updatedUserInfo.avatar = avatarFileID;
          }
          
          // 更新本地数据
          this.userInfo = updatedUserInfo;
          
          // 更新uni-id-pages存储的用户信息
          const storageUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
          const newUserInfo = {
            ...storageUserInfo,
            ...updateData
          };
          
          // 如果头像已更新，将新头像添加到本地存储
          if (avatarFileID) {
            newUserInfo.avatar = avatarFileID;
          }
          
          // 删除不需要存储在本地的字段
          delete newUserInfo.uid;
          
          uni.setStorageSync('uni-id-pages-userInfo', newUserInfo);
          mutations.updateUserInfo(newUserInfo);
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          this.closeEditProfile();
          
          // 刷新用户信息
          this.loadUserInfo();
        } else {
          // 更详细的错误信息
          console.error('更新用户失败, 详细信息:', result);
          throw new Error(result.message || `更新失败(${result.code})`);
        }
      } catch (error) {
        // 增强错误日志
        console.error('保存个人资料失败:', error);
        if (error.code) {
          console.error('错误代码:', error.code);
        }
        if (error.errCode) {
          console.error('错误代码(errCode):', error.errCode);
        }
        
        uni.hideLoading();
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none',
          duration: 3000
        });
        
        // 显示更多详细错误信息
        uni.showModal({
          title: '保存失败',
          content: `详细错误: ${JSON.stringify(error)}`,
          showCancel: false
        });
      }
    },
    
    // 退出登录
    async logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 使用uni-id-co云对象登出
              const uniIdCo = uniCloud.importObject("uni-id-co");
              await uniIdCo.logout();
              
              // 更新本地存储状态
              mutations.logout();
              
              // 跳转到登录页
              uni.reLaunch({
                url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
              });
            } catch (error) {
              console.error('退出登录失败:', error);
              // 即使接口失败也执行本地清理
              mutations.logout();
              uni.reLaunch({
                url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
              });
            }
          }
        }
      });
    },
    
    // 跳转到收藏页面
    goToFavorites() {
      uni.navigateTo({
        url: '/pages/favorites/index'
      })
    },
    
    // 跳转到账户安全设置
    goToAccountSecurity() {
      uni.navigateTo({
        url: '/pages/profile/security'
      })
    },
    
    // 跳转到通知设置
    goToNotificationSettings() {
      uni.navigateTo({
        url: '/pages/profile/notifications'
      })
    },
    
    // 跳转到隐私设置
    goToPrivacySettings() {
      uni.navigateTo({
        url: '/pages/profile/privacy'
      })
    },
    
    // 跳转到关于我们
    goToAbout() {
      uni.navigateTo({
        url: '/pages/profile/about'
      })
    },
    
    viewPattern(pattern) {
      uni.navigateTo({
        url: `/pages/pattern/detail?id=${pattern.id}&name=${pattern.name}`
      })
    },
    
    goToHome() {
      uni.switchTab({
        url: '/pages/device/list'
      })
    },
    
    goToExplore() {
      uni.switchTab({
        url: '/pages/explore/index'
      })
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-blue-100 { background-color: #dbeafe; }
.bg-blue-500 { background: linear-gradient(135deg, #3b82f6, #2563eb); }
.bg-blue-600 { background: linear-gradient(135deg, #2563eb, #1d4ed8); }
.bg-black { background-color: #000000; }

.bg-white-20 { background-color: rgba(255, 255, 255, 0.2); }
.bg-opacity-50 { background-color: rgba(0, 0, 0, 0.5); }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-700 { color: #374151; }
.text-gray-900 { color: #111827; }
.text-blue-100 { color: #dbeafe; }
.text-blue-500 { color: #3b82f6; }

.h-screen { height: 100vh; }
.h-20 { height: 160rpx; }
.h-24 { height: 192rpx; }
.h-16 { height: 128rpx; }
.w-8 { width: 64rpx; }
.w-16 { width: 128rpx; }
.w-20 { width: 160rpx; }
.w-24 { width: 192rpx; }
.w-32 { width: 256rpx; }
.h-8 { height: 64rpx; }
.w-full { width: 100%; }
.h-full { height: 100%; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.flex-shrink-0 { flex-shrink: 0; }

.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.py-2 { padding-top: 16rpx; padding-bottom: 16rpx; }
.py-3 { padding-top: 24rpx; padding-bottom: 24rpx; }
.pt-6 { padding-top: 48rpx; }
.pt-12 { padding-top: 96rpx; }
.pb-6 { padding-bottom: 48rpx; }
.pb-8 { padding-bottom: 64rpx; }
.p-3 { padding: 24rpx; }
.p-4 { padding: 32rpx; }
.px-4 { padding-left: 32rpx; padding-right: 32rpx; }

.mb-1 { margin-bottom: 8rpx; }
.mb-2 { margin-bottom: 16rpx; }
.mb-4 { margin-bottom: 32rpx; }
.mb-6 { margin-bottom: 48rpx; }
.mr-1 { margin-right: 8rpx; }
.mt-1 { margin-top: 8rpx; }

.border { border-width: 1rpx; }
.border-2 { border-width: 2rpx; }
.border-t { border-top-width: 1rpx; }
.border-b { border-bottom-width: 1rpx; }
.border-b-2 { border-bottom-width: 2rpx; }
.border-gray-100 { border-color: #f3f4f6; }
.border-gray-200 { border-color: #e5e7eb; }
.border-gray-300 { border-color: #d1d5db; }
.border-blue-500 { border-color: #3b82f6; }
.border-dashed { border-style: dashed; }

.rounded-xl { border-radius: 24rpx; }
.rounded-lg { border-radius: 16rpx; }
.rounded-full { border-radius: 9999px; }
.rounded-t-3xl { border-top-left-radius: 48rpx; border-top-right-radius: 48rpx; }

.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.justify-around { justify-content: space-around; }

/* 个人中心顶部样式 */
.profile-header {
  position: relative;
  padding: 64rpx 48rpx 32rpx;
  min-height: 400rpx;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0.95;
}

.header-background::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.15"/><circle cx="10" cy="50" r="0.5" fill="white" opacity="0.15"/><circle cx="90" cy="30" r="0.8" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
  opacity: 0.3;
}

.header-content {
  position: relative;
  z-index: 2;
}

.profile-avatar-container {
  position: relative;
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.2);
}

.profile-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48rpx;
}

.avatar-edit-overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid white;
}

.edit-profile-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  padding: 16rpx 24rpx;
  border-radius: 50rpx;
  color: white;
  font-size: 28rpx;
  backdrop-filter: blur(10rpx);
  transition: all 0.3s ease;
}

.edit-profile-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 收藏集横向滚动样式 */
.collection-scroll-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
}

.collection-scroll-wrapper {
  display: inline-flex;
  gap: 32rpx;
  padding: 24rpx 0;
  min-width: 100%;
}

.collection-item {
  flex-shrink: 0;
  width: 240rpx;
}

.collection-card {
  width: 100%;
  height: 180rpx;
  background: #f9fafb;
  border-radius: 24rpx;
  padding: 24rpx;
  border: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  position: relative;
  transition: all 0.2s ease;
}

.collection-card:hover {
  border-color: #3b82f6;
  background: #f8faff;
}

.collection-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8rpx;
  line-height: 1.3;
}

.collection-count {
  font-size: 24rpx;
  color: #6b7280;
}

.add-card {
  background: #f3f4f6;
  border: 2px dashed #d1d5db;
  justify-content: center;
  align-items: center;
}

.collection-add-icon {
  font-size: 48rpx;
  color: #9ca3af;
  margin-bottom: 8rpx;
}

.collection-add-text {
  font-size: 24rpx;
  color: #6b7280;
  font-weight: 500;
}

/* 退出登录按钮样式 */
.logout-btn {
  width: 100%;
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
  border-radius: 24rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(239, 68, 68, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  min-height: 100rpx;
}

/* 头像上传组件样式 */
.avatar-upload-container {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  border: 6rpx solid #ffffff;
  margin-bottom: 16rpx;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  background-color: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 80rpx;
  color: #d1d5db;
}

.avatar-upload-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32rpx;
}

.logout-btn:active {
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 8rpx rgba(239, 68, 68, 0.4);
}

.logout-btn text {
  color: white;
  font-size: 32rpx;
  font-weight: 600;
}

.text-left { text-align: left; }
.text-center { text-align: center; }
.text-xl { font-size: 40rpx; }
.text-lg { font-size: 36rpx; }
.text-sm { font-size: 28rpx; }
.text-xs { font-size: 24rpx; }
.text-2xl { font-size: 48rpx; }
.text-3xl { font-size: 56rpx; }

.font-bold { font-weight: bold; }
.font-semibold { font-weight: 600; }
.font-medium { font-weight: 500; }

.block { display: block; }

.space-x-2 > view:not(:first-child) { margin-left: 16rpx; }
.space-x-3 > view:not(:first-child) { margin-left: 24rpx; }
.space-x-4 > view:not(:first-child) { margin-left: 32rpx; }
.space-x-6 > view:not(:first-child) { margin-left: 48rpx; }
.space-y-3 > view:not(:first-child) { margin-top: 24rpx; }

.aspect-square { aspect-ratio: 1/1; }

.grid { display: grid; }
.grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.gap-4 { gap: 32rpx; }

.overflow-hidden { overflow: hidden; }
.overflow-auto { overflow: auto; }
.overflow-x-auto { overflow-x: auto; }

.object-cover { object-fit: cover; }

.shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }

.leading-tight { line-height: 1.25; }
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.-mx-6 { margin-left: -48rpx; margin-right: -48rpx; }

.transition-colors { transition: color 0.2s ease, background-color 0.2s ease; }
.transition-opacity { transition: opacity 0.3s ease; }

.hover\:text-blue-600:hover { color: #2563eb; }
.hover\:text-blue-500:hover { color: #3b82f6; }
.hover\:border-blue-500:hover { border-color: #3b82f6; }
.hover\:opacity-100:hover { opacity: 1; }

.focus\:border-blue-500:focus { border-color: #3b82f6; }
.focus\:ring-2:focus { box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1); }
.focus\:ring-blue-200:focus { box-shadow: 0 0 0 2px rgba(147, 197, 253, 0.5); }
.outline-none { outline: none; }

.opacity-0 { opacity: 0; }
.opacity-100 { opacity: 1; }

/* 底部弹窗动画 */
.bottom-sheet {
  transform: translateY(100%);
  transition: transform 0.3s ease-in-out;
}
.bottom-sheet.active {
  transform: translateY(0);
}

/* 底部安全区域，防止被底部导航栏遮挡 */
.safe-area-bottom {
  padding-bottom: calc(8rpx + 120rpx); /* 原有的pb-8加上底部导航栏的高度 */
  /* 在iOS设备上增加底部安全区域高度 */
  padding-bottom: constant(safe-area-inset-bottom, 120rpx);
  padding-bottom: env(safe-area-inset-bottom, 120rpx);
}

.overlay {
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  pointer-events: none;
}
.overlay.active {
  opacity: 1;
  pointer-events: auto;
}

.hidden { display: none; }

.fixed { position: fixed; }
.absolute { position: absolute; }
.relative { position: relative; }
.inset-0 { top: 0; right: 0; bottom: 0; left: 0; }
.bottom-0 { bottom: 0; }
.left-0 { left: 0; }
.right-0 { right: 0; }
.z-40 { z-index: 40; }
.z-50 { z-index: 50; }

/* Font Awesome 图标 */
.fas {
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
}

.fa-cog:before { content: "\f013"; }
.fa-globe:before { content: "\f0ac"; }
.fa-chevron-right:before { content: "\f054"; }
.fa-plus:before { content: "\f067"; }
.fa-user:before { content: "\f007"; }
.fa-home:before { content: "\f015"; }
.fa-compass:before { content: "\f14e"; }
.fa-times:before { content: "\f00d"; }
.fa-camera:before { content: "\f030"; }
.fa-check:before { content: "\f00c"; }
.fa-edit:before { content: "\f044"; }
.fa-shield-alt:before { content: "\f3ed"; }
.fa-bell:before { content: "\f0f3"; }
.fa-user-secret:before { content: "\f21b"; }
.fa-info-circle:before { content: "\f05a"; }
.fa-sign-out-alt:before { content: "\f2f5"; }
</style>
